package com.yuneec.droneservice.request;

import com.yuneec.droneservice.DroneService;
import com.yuneec.droneservice.tools.RCLog;

import java.lang.ref.WeakReference;
import java.util.List;

/**
 * Created by zd.zhang on 2017/10/31.
 */

public class OnListenerHandler<T> implements IResponseHandler {
    private WeakReference<DroneService.DroneBinder> binderReference;
    private int id;
    private T t;

    public OnListenerHandler(int id, T t, DroneService.DroneBinder binder) {
        this.id = id;
        this.t = t;
        this.binderReference = new WeakReference<>(binder);
    }

    @Override
    public int ids() {
        return -1;
    }

    @Override
    public void run() {
        try {
            if (t == null) {
                return;
            }
            DroneService.DroneBinder binder = binderReference.get();
            if (binder == null) {
                return;
            }

            List<OnListener<?>> listeners = binder.getListener(id);
            if (listeners == null) {
                return;
            }
            for (OnListener<?> listener : listeners) {
                OnListener<T> l = (OnListener<T>) listener;
                l.onListener(t);
            }
        } catch (Exception e) {
            RCLog.d("OnListenerHandler.error:", e);
        }
    }

    public T get() {
        return t;
    }

    public void set(T t) {
        this.t = t;
    }
}
